<?php
/**
 * Description of PresentacionP
 *
 * @author Nelifer
 */
include_once('BDManager.class.php');

class Inventario {
    var $con;
    function Inventario(){
        $this->con=new BDManager();
    }

    function insertarInventario($tipoProd = null, $prodId, $cant = null){
        $invId = 0;
        $invCant = 0;
        
        if($this->con->conectar()==true){
            $res1 = false;
            $res2 = false;
            $mapId = 'NULL';
            $pteId = 'NULL';
            if($tipoProd == 1){
                $mapId = $prodId;
            }else if($tipoProd == 2){
                $pteId = $prodId;
            }
            
            if (!$this->existeProducto($prodId, $tipoProd)){
                $invCant = $invCant + abs($cant);
                $sql1 = "INSERT INTO inventarios (inv_tipo, map_id, pte_id, inv_canttotal) VALUES('".$tipoProd."', ".$mapId.", ".$pteId.", '".$invCant."')";
                $res1 = mysql_query($sql1);	

                $BD = new BDManager();
                $invId = $BD->get_current_insert_id("inventarios");

            }else{
                $res = $this->getCantidadInv( $prodId, $tipoProd );
               
                if( $row = mysql_fetch_array( $res ) ){
                    $invId  = $row["inv_id"];
                    $invCant= $row["inv_canttotal"];
                }
                $invCant = $invCant + $cant;
                $sql1 = "UPDATE inventarios SET inv_canttotal = '".abs($invCant)."' WHERE inv_id = '".$invId."';" ;
                //echo "SQl1: $sql1";
                $res1 = mysql_query($sql1);
            }
            return ($res1)  ? $invId : -1;
        }
    }

    public function insertarRegistroInv($invId, $cant, $fecha, $hora, $usuId){
        if($this->con->conectar()==true){
            $sql = "INSERT INTO registrosinventarios (inv_id, reg_cantidad, reg_fecha, reg_hora, usu_id) ".
                   "VALUES ('".$invId."', '".$cant."', '".$fecha."', '".$hora."', '".$usuId."')";
            $res1 = mysql_query($sql);             
            return $res1;            
        }		
    }

    public function getConsulta($id){
        if($this->con->conectar()==true){
            $sql = "SELECT inv.inv_id, inv.inv_tipo, inv.map_id, inv.pte_id ".
                    "FROM inventarios inv ".                
                    "WHERE inv.inv_id=$id ";
            return mysql_query($sql);
        }
    }

    public function getCantidad($id){
        $cant = 0;
        if($this->con->conectar()==true){
            $res =  mysql_query("SELECT inv.inv_canttotal FROM inventarios inv where inv.inv_id = $id");
            
            if( $row = mysql_fetch_array($res) ){
                $cant = $row['inv_canttotal'] ;
            }
        }
        return $cant;
    }

    function eliminar($id){
        if($this->con->conectar()==true){
                return mysql_query("DELETE FROM ordenescompras WHERE odc_id=".$id);
        }
    }
    private function getCantidadInv($prodId = null, $tipoProd = null){
        $mapId = 0;
        $pteId = 0;
        if($tipoProd==1){
            $mapId = $prodId;
        }else if($tipoProd==2){
            $pteId = $prodId;
        }
         if($this->con->conectar()==true){
            $sql = "SELECT inv.inv_id, inv.inv_canttotal ".
                    "FROM inventarios inv ".                
                    "WHERE  (inv.map_id=$mapId or $mapId = 0) AND (inv.pte_id = $pteId or $pteId = 0) AND inv.inv_tipo = $tipoProd";

            return mysql_query($sql);
            
        }
        
    }
    public function existeProducto($prodId = null, $tipoProd = null){
        $mapId = 0;
        $pteId = 0;
        if($tipoProd==1){
            $mapId = $prodId;
        }else if($tipoProd==2){
            $pteId = $prodId;
        }
         if($this->con->conectar()==true){
            $sql = "SELECT inv.inv_id ".
                    "FROM inventarios inv ".                
                    "WHERE (inv.map_id=$mapId or $mapId = 0) AND (inv.pte_id = $pteId or $pteId = 0) AND inv.inv_tipo = $tipoProd";
            
            $result = mysql_query($sql);
            $total = mysql_num_rows($result);
            return (($total > 0) ? true : false);
        }
    }
    private function countRec($fname,$tname,$where) {
        $con = null;
        $sql = "SELECT count($fname) FROM $tname $where";
        if($this->con->conectar()==true){
            $con = $this->con->conectar();
            $result = mysql_query($sql);
        }
        while ($row = mysql_fetch_array($result)) {
            return $row[0];
        }
    }
    
    public function consultar_grid($page=null, $rp=null, $sortname=null, $sortorder=null, $query=null, $letter_pressed=null, $qtype=null, $tipoProducto=null){
        if (!$sortname) $sortname = 'name';
        if (!$sortorder) $sortorder = 'desc';
        if($query!=''){
             $where = "WHERE `".$qtype."` LIKE '%".$query."%' ";
        } else {
            $where ='';
        }
        if($letter_pressed!=''){
            $where = "WHERE `".$qtype."` LIKE '".$letter_pressed."%' ";	
        }
        if($letter_pressed=='#'){
            $where = "WHERE `".$qtype."` REGEXP '[[:digit:]]' ";
        }
        $sort = "ORDER BY $sortname $sortorder";

        if (!$page) $page = 1;
        if (!$rp) $rp = 10;
        $start = (($page-1) * $rp);
        $limit = "LIMIT $start, $rp";
        $sql = "SELECT odc.odc_id, odc.odc_codigo, pro.pro_razonsocial, odc.odc_fechacreacion, ".
                      "CONCAT(usu.usu_nombre, ' '  ,usu.usu_apellido) usu_nombre  ".
                "FROM ordenescompras odc ".
                      "INNER JOIN proveedores pro on pro.pro_id = odc.pro_id ".
                      "INNER JOIN usuarios usu on usu.usu_id = odc.usu_id $where $sort $limit";

        $total = $this->countRec('odc_id','ordenescompras',$where);

        $con = $this->con->conectar();
        $result = mysql_query($sql);
        //$this->con->close($con); OJO CERRAR CONEXIONES

        // Return JSON data
        $data = array();
        $data['page'] = $page;
        $data['total'] = $total;
        $data['rows'] = array();

        while ($row = mysql_fetch_assoc($result)) {
            $data['rows'][] = array(
            'id' => $row['odc_id'],
            'cell' => array($row['odc_id'], $row['odc_codigo'], $row['pro_razonsocial'], $row['odc_fechacreacion'],
                            $row['usu_nombre'])
            );
        }

        echo json_encode($data);
    }
 
    public function getConsultasReporteServicioProducto( $fechaIni, $fechafin){
        if($this->con->conectar()==true){
            $condicion = "";
            if($fechaIni>0 && $fechafin>0)
                $condicion = " WHERE fve.fve_fechacreacion BETWEEN $fechaIni and $fechafin ";
            $sql = "SELECT pte.pte_codigo pro_codigo, pte.pte_nombre pro_nombre, SUM(ifv.ifv_cantordenada) ifv_cantordenada, ".
                   "COALESCE(SUM(ifv.ifv_cant),0) ifv_cant " .
                   "FROM facturasventas fve ".
                   "INNER JOIN itemsfacturasventas ifv on ifv.fve_id = fve.fve_id  ".
                   "INNER JOIN productosterminados pte ON pte.pte_id = ifv.pte_id ".
                   " $condicion " .
                   "GROUP BY  pte.pte_codigo, pte.pte_nombre ".
                   "ORDER BY pte.pte_codigo ASC ";
            return mysql_query($sql);
        }
    }
    public function getConsultasReporteServicioCliente( $fechaIni, $fechafin){
        if($this->con->conectar()==true){
            $condicion = "";
            if($fechaIni>0 && $fechafin>0)
                $condicion = " WHERE fve.fve_fechacreacion BETWEEN $fechaIni and $fechafin ";
            $sql = "SELECT cli.cli_rif, cli.cli_razonsocial, CONCAT(fve.fve_nrocontrol, '/' ,fve.fve_nro) fve_nro, " .
                   "CONCAT(pte.pte_codigo, ' / ',pte.pte_nombre) pro_nombre, ".
                   "SUM(ifv.ifv_cantordenada) ifv_cantordenada, COALESCE(SUM(ifv.ifv_cant),0) ifv_cant ".
                   "FROM facturasventas fve ".
                   "INNER JOIN itemsfacturasventas ifv on ifv.fve_id = fve.fve_id ".
                   "INNER JOIN productosterminados pte ON pte.pte_id = ifv.pte_id ".
                   "INNER JOIN clientes cli ON cli.cli_id = fve.cli_id ".
                   " $condicion ".
                   "GROUP BY  cli.cli_rif, cli_razonsocial, pte.pte_codigo, pte.pte_nombre, fve.fve_nrocontrol, fve.fve_nro ".
                   "ORDER BY cli.cli_rif, cli.cli_razonsocial ASC ";
            //echo "SQL: $sql";
            return mysql_query($sql);
        }
    }
}

?>
